import React from 'react'
// ===================================================================== antd
import { DownCircleOutlined } from '@ant-design/icons'
// ===================================================================== Declare
const { $fn, $Lazy } = window
// ===================================================================== Lazy
const Form 				= $Lazy.hook(()=>import('@antd/form/layout/form'))
const FormItem 			= $Lazy.load(()=>import('@antd/form/layout/item'))
const Button			= $Lazy.load(()=>import('@antd/button'))
const Input 			= $Lazy.load(()=>import('@antd/form/input'))
const Select 			= $Lazy.load(()=>import('@antd/form/select'))
const TreeSelect 		= $Lazy.load(()=>import('@antd/form/treeSelect'))
const DatePicker 		= $Lazy.load(()=>import('@antd/form/datePicker'))
const DatePickerRange 	= $Lazy.load(()=>import('@antd/form/datePickerRange'))
const Checkbox 			= $Lazy.load(()=>import('@antd/form/checkbox'))
// const Switch 		= $Lazy.load(()=>import('@antd/form/switch'))
// const SelectInput 	= $Lazy.load(()=>import('@antd/form/select-input'))
// =====================================================================
const bordered = false
const size = 'small'
let flag = null
const SearchForm = ({ children, data=[], onChange, max=5, controls, form, hasMany = false, hasAuto=true, expands, bind, loading, onSubmit, onSetHeader, onReset, onRefesh, className, labelWidth, init, submitText, code, suffix, noRefresh, disabled, noReset }) => {
	const boxRef = React.useRef()
	const arrowRef = React.useRef()
	const [ btns, setBtns] = React.useState([
		{ label:'搜索', code:'F4', ghost:false, onClick: onSubmit  },
		{ label:'重置', code:'F6', ghost:true, onClick: onReset, hide: noReset },
		onSetHeader && { label:'设置表头', ghost:true, onClick: onSetHeader },
		{ label:'刷新', code:'F9', ghost:true, onClick: ()=>{ $fn.refreshRouter() }, hide: noRefresh },
	])
	
	React.useEffect(()=>{
		if($fn.hasArray(controls)){ setBtns([...controls]) }
		if(!flag){
			if($fn.hasArray(expands)){ setBtns( b => {
				flag = true
				return [ ...b, ...expands ]
			}) }
		}
	},[controls, expands])
	
	// 初始化执行
	const _init = React.useCallback( v => {
		init && init(v, data)
	},[init, data])
	
	const onChanged = React.useCallback( (option, v, type) => {
		onChange?.(option)
		
		v.onValue?.({...option, ref:form, form:'forms', data, forms:data})
		/* 点击查询按钮或按查询快捷键后才触发查询条件 2021-08-26  --耿琰 */
		// if(type !== undefined && type !== 'textarea' && v.mode!=='multiple'){
		// 	onSubmit()
		// }else{
		// 	if(option.value === '' && type ){ onSubmit() } 
		// }
	}, [onChange, data, form])
	
	const _hasMany = (Array.isArray(data)&&data.length > max && hasMany === true)
	return (
		<div className={`xplr bcf ${className||'pt10 pb5'} ${ _hasMany?'too-many-search too-many-search-' + max:''}`}>
			<Form dir='x' onSubmit={onSubmit} init={_init} className={`fxw search-form small-form ${labelWidth? labelWidth + ' right' : ''}`}>
				<div className='ex' style={{height:28,overflow:'hidden'}}>
					<div ref={boxRef}>
						<div className='fxw'>
							{
								$fn.hasArray(data) &&  data.map((v,i)=>{
									const { type, value, label, data, name, names, format, readOnly } = v
									const width = v.width || 150
									const mr = 20
									const _disabled = loading || ($fn.isValid(v.disabled) ? v.disabled : disabled)
									// 可读
									// const _readOnly = readOnly ? readOnly : v.readOnly
									
									let children = null
									if(type === 'select'){ // 下拉框
										children = <Select
											name		= { name }
											size		= { size }
											width		= { width }
											bordered	= { bordered }
											value		= { value }
											disabled	= { _disabled }
											loading 	= { v.loading }
											readOnly	= { readOnly }
											p			= {`请选择` + label}
											onChanged	= { option => onChanged.call(null, option, v, type) }
											// private
											data		= { data } 
											nameStr		= { v.nameStr } 
											idStr		= { v.idStr }
											mode		= { v.mode }
											btn			= { v.btn }
											isClear 	= { v.isClear }
											outer		= { v.outer }
											auto
										/> 
									}else if(type === 'select-input'){	// 条件选择
										// children = <SelectInput
										// 	name		= { names }
										// 	size		= { size }
										// 	bordered 	= { bordered } 
										// 	disabled	= { _disabled } 
										// 	readOnly	= { _readOnly } 
										// 	required	= { v.required }
										// 	onChanged	= { option => onChanged.call(null, option) }
										// 	data		= { v.data }
										// 	idStr		= { v.idStr }
										// 	nameStr		= { v.nameStr }
										// 	label 		= { v.label }
										// />
									}else if(type === 'treeSelect'){	// 下拉框
										children = <TreeSelect
											name		= { name }
											size		= { size }
											width		= { width }
											bordered	= { bordered }
											disabled	= { _disabled }
											readOnly	= { readOnly }
											p			= {'请选择' + label}
											// private
											filterName =  { v.filterName }
											data		= { v.data } 
											nameStr		= { v.nameStr } 
											idStr		= { v.idStr }  
											auto 
											onChanged	= { option => onChanged.call(null, option, v, type) }
											checkable	={ v.checkable }
											multiple	={ v.multiple }
										/> 
									}else if(type === 'date-range'){ // 日期范围
										// children = <DatePicker 
										// 	name		= { names }
										// 	size		= { size }
										// 	width		= { width * 2 + 30 }
										// 	bordered	= { bordered }
										// 	disabled	= { _disabled }
										// 	readOnly	= { readOnly }
										// 	onChanged	= { option => onChanged.call(null, option, v, type) }
										// 	// private
										// 	range 
										// 	showTime
										// 	format		= { format } 
										// />
										children = <DatePickerRange
											name		= { names }
											size		= { size }
											width		= { format === 1 ? 120 : 180 }
											bordered	= { bordered }
											disabled	= { _disabled }
											readOnly	= { readOnly }
											onChanged	= { option => onChanged.call(null, option, v, type) }
											showTimeStart
											showTimeEnd
											outer
											// private
											showTime
											format		= { format }
										/>
									}else if(type === 'date-time'){ // 日期
										children = <DatePicker 
											name		= { name }
											size		= { size } 
											width		= { width }
											bordered	= { bordered }
											value		= { value }
											disabled	= { _disabled }
											readOnly	= { readOnly }
											onChanged	= { option => onChanged.call(null, option, v, type) }
											// private
											showTime
											picker		= { v.picker }
											format		= { v.format }
											after		= { v.after }
										/>
									}else if(type === 'checkbox') {	// 复选框
										children = <Checkbox
											isNumber
											name		= { name }
											label 		= { v.tag ? v.tag : (v.after ? v.label : null) }
											size		= { size }
											value		= { value }
											disabled	= { _disabled }
											readOnly	= { readOnly }
											onChanged	= { option => onChanged.call(null, option, v, type) }
										/> 
									}else if(type === 'switch') {		// 开关
										// children = <Switch 
										// 	name		= { name }
										// 	size		= { size }
										// 	value		= { value }
										// 	disabled	= { _disabled }
										// 	readOnly	= { readOnly }
										// 	onChanged	= { option => onChanged.call(null, option, v, type) }
										// /> 
									}else{	// 输入框
										children = <Input
											name		= { name }
											size		= { size }
											bordered 	= { bordered } 
											value		= { value }
											disabled	= { _disabled } 
											p			= { v.p ?  v.p : '请输入' + label }
											mode 		= { v.type }
											onClick		= { v.onClick }
											onKeyup		= { v.onKeyup }
											onEnter 	= { v.onPressEnter ? v.onPressEnter : onSubmit }
											autoFocus	= { v.autoFocus }
											btn			= { v.btn }
											onChanged	= { option => onChanged.call(null, option, v, type) }
											outer
											id			= { v.id }
										/>
									}
									return (
										<React.Fragment key={i}>
											{
												!v.hide ? (
													<FormItem
														style		= {v.style}
														label		= { label ? label : null } 
														name		= { type === 'date-range' ? (name ? name : 'jz-time') : name }
														mr			= { mr }
														colon		= { v.colon }
														className = {`
															${label ? '' : 'no-label'} 
															${type==='date-time'?'date-time-picker':''}
															${type==='date-range'?'data-range':''}
															${_disabled ? 'form-disabled' : ''}
														`}
													>	
														{children}
													</FormItem>
												) : null
											}
										</React.Fragment>
									)
								})
							}
						</div>
					</div>
				</div>
				<div className='ml5 fx'>
					{
						btns.map((v,i)=> ($fn.hasObject(v) && v.hide !== true) && <Button key={i} code={code===false ? null : v.code} onClick={v.onClick} className={ i>0 ? 'ml10' : '' } disabled={disabled||loading||v.disabled} htmlType={v.htmlType} label={v.label} ghost={v.ghost}/> )
					}
					{
						_hasMany || hasAuto ? (
							<div className={`h24 ml5 fxmc expand-btn`} ref={arrowRef} style={{display: boxRef.current?.clientHeight > 30 ? 'flex' : 'none' }} onClick={()=>{
								// rotate-up
								const $parent = boxRef.current.parentNode
								
								if($parent.style.overflow === 'hidden'){
									arrowRef.current.style.transform = 'rotate(-180deg)'
									$parent.style.height = 'auto'
									$parent.style.overflow = 'visible'
								}else{
									arrowRef.current.style.transform = 'rotate(0)'
									$parent.style.height = '28px'
									$parent.style.overflow = 'hidden'
								}
							}}>
								<DownCircleOutlined style={{color:$fn.c0, fontSize:20}} />
							</div>
						) : null
					}
					{ suffix }
				</div>
			</Form>
		</div>
	)
}

class Index extends React.Component{
	
	
	componentDidMount(){
		
	}
	
	componentWillUnmount(){
		
	}
	
	// 初始化并设置默认值
	init = form => {
		const { data, onForm, value } = this.props
		this.form = form
		// 如果有默认值，才设置默认值
		
		if(value){ 
			this.setValue(value)
		}
		onForm && onForm(this, form)
		// 检测是否有默认值 value
		if($fn.hasArray(data)){
			const values = data.filter(v => $fn.isValid(v))
			if($fn.hasArray(values)){
				this.setDataValue(values)
			}
		}
	}
	// 将表单元素列表数据上的值绑定到表单
	setDataValue = data => {
		if($fn.hasArray(data)){
			data.forEach(m=>{
				this.form.setFieldsValue({ [m.name] : m.value })
			})
		}
	}
	// 设置默认值
	setValue = value => {
		if($fn.hasObject(value)){
			this.form.setFieldsValue(value)
		}else{
			this.setDataValue(value)
		}
	}
	// 获取 name 字段的值
	getName = name => this.form.getFieldValue(name)
	// 提交表单
	submit = () => this.form.submit()
	// 获取 name 字段的值
	getValue = names => this.form.getFieldsValue(names)
	// 重置表单
	reset = names => {
		this.form.resetFields()
		this.props?.onReset?.()
	}
	
	render(){
		const { children } = this.props
		return (
			<SearchForm
				{...this.props}
				init		= { this.init }
				form		= { this }
				onRefesh	= { () => $fn.refreshRouter() }
				onReset		= { () => this.reset() }
			>
				{children}
			</SearchForm>
		)
	}
}
export default Index